package com.sav.common.auth;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.sav.common.dao.UserDAO;



public class CustomAuthenticationProvider implements UserDetailsService {

	@Autowired(required=true)
	UserDAO userDAO;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		com.sav.common.catalog.User user = userDAO.getUserByName(username);
		if (user == null)
			throw new UsernameNotFoundException("Invalid username/password.");

		List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
		List<String> roles = userDAO.getRoles(username);
		for (String r : roles) {
			AUTHORITIES.add(new SimpleGrantedAuthority(r));
		}
		return new User(user.getLogin(), user.getPassword(), AUTHORITIES);
	}
} 

